package com.lagou.edu.service.impl;

import com.lagou.edu.CodeServiceTwo;
import com.lagou.edu.dao.LagouAuthTokenDao;
import com.lagou.edu.pojo.LagouAuthToken;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;

import java.util.Date;
import java.util.List;

@Service
public class CodeServiceTwoImpl implements CodeServiceTwo {

    @Autowired
    private LagouAuthTokenDao lagouAuthTokenDao;

    public Integer validateCode(String email, String code) {
        Date now = new Date();

        //获取到最新一条token数据
        Sort createTime = new Sort(Sort.Direction.DESC, "createtime");
        LagouAuthToken lagouAuthToken = new LagouAuthToken();
        lagouAuthToken.setEmail(email);
        Example<LagouAuthToken> example = Example.of(lagouAuthToken);
        List<LagouAuthToken> all = lagouAuthTokenDao.findAll(example, createTime);
        if (all != null && all.size() > 0) {
            LagouAuthToken rToken = all.get(0);
            //0正确1错误2超时
            if (rToken != null && code.equals(rToken.getCode())) {
                if (now.before(rToken.getExpiretime())) {
                    return 0;
                } else {
                    return 2;
                }
            } else {
                return 1;
            }
        } else {
            return 1;
        }
    }
}
